package junitrunner;

import org.apache.commons.cli.*;
import org.apache.commons.io.FileUtils;
import org.junit.internal.TextListener;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;

import java.io.File;
import java.io.IOException;

public class Runner {
    private File reportDirectory;

    public static void main(String[] args) throws ParseException, IOException, ClassNotFoundException {
        boolean success = new Runner().run(args);
        System.exit(success ? 0 : 1);


    }

    public  boolean run(String[] args) throws ParseException, IOException, ClassNotFoundException {
        Options options = new Options();

        Option option = new Option("o", "report-directory", true, "Directory for the xml reports");
        option.setRequired(true);
        options.addOption(option);

        CommandLineParser parser = new GnuParser();
        CommandLine cmd = parser.parse( options, args);
        final File reportDirectory = new File(cmd.getOptionValue("o"));

        FileUtils.deleteDirectory(reportDirectory);
        this.reportDirectory = reportDirectory;
        this.reportDirectory.mkdirs();

        return  runTests(cmd.getArgs());

    }

    private boolean runTests(String[] classNames) throws ClassNotFoundException {

        JUnitCore runner = new JUnitCore();
        final XmlWritingListener writingListener = new XmlWritingListener(reportDirectory);
        runner.addListener(new TextListener(System.out));
        runner.addListener(writingListener);


        boolean success = true;

        for (String className : classNames){
            final Class<?> aClass = this.getClass().getClassLoader().loadClass(className);
            writingListener.startFile(aClass);
            Result result;
            result = runner.run(aClass);
            success = success && result.wasSuccessful();
            writingListener.closeFile();
        }

        return success;


        

    }


}
